package cn.xuchunh.campusbbs.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.bean.User;

/**
 * Created by XuChunH on 2015/9/9.
 */
public abstract class BaseFragment extends Fragment {

    private int contentViewRes = -1;

    private OnFragmentInteractionListener listener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleArgs(getArguments());
        beforeInitView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (contentViewRes != -1) {
            return createView(inflater, container, savedInstanceState);
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        afterInitView();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            listener = (OnFragmentInteractionListener) context;
        }
    }

    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(contentViewRes, container, false);
    }

    protected abstract void initView(View view);

    protected abstract void beforeInitView();

    protected void afterInitView() {
    }

    protected void setTitle(CharSequence title) {
        ((BaseActivity) getContext()).setTitle(title);
    }

    protected void showToast(String message) {
        Toast.makeText(AppContext.getInstance(), message, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(int messageRes) {
        showToast(getString(messageRes));
    }

    public User getUser() {
        return AppContext.getInstance().getUser();
    }

    protected void setContentViewRes(int contentViewRes) {
        this.contentViewRes = contentViewRes;
    }

    protected int getContentViewRes() {
        return contentViewRes;
    }

    protected void handleArgs(Bundle args) {
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Bundle data);
    }

    public OnFragmentInteractionListener getListener() {
        return listener;
    }
}
